package scanpackage.future;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import scanpackage.generator.ResponseGenerator;

import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;

@Service
public class CustomFutureCallback implements FutureCallback<HttpResponse> {
    private  HttpGet httpGet;
    private  FullHttpRequest inbound;
    private  ChannelHandlerContext ctx;

    public HttpGet getHttpGet() {
        return httpGet;
    }

    public void setHttpGet(HttpGet httpGet) {
        this.httpGet = httpGet;
    }

    public FullHttpRequest getInbound() {
        return inbound;
    }

    public void setInbound(FullHttpRequest inbound) {
        this.inbound = inbound;
    }

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    public void setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public void completed(HttpResponse endpointResponse) {
        try {
            handleResponse(inbound, ctx, endpointResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed(Exception ex) {
        this.httpGet.abort();
        ex.printStackTrace();
    }

    @Override
    public void cancelled() {
        this.httpGet.abort();
    }

    public void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception {
        FullHttpResponse response = null;
        try {
            //优先判断响应是否出现401
            byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity());
            response= ResponseGenerator.getResponse(OK,Unpooled.wrappedBuffer(body),endpointResponse);
        }
        catch (Exception e) {
            e.printStackTrace();
            response= ResponseGenerator.getResponse(NO_CONTENT,Unpooled.wrappedBuffer("NO_CONTENT".getBytes()),endpointResponse);
        } finally {
            if (fullRequest != null) {
                if (!HttpUtil.isKeepAlive(fullRequest)) {
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else {
                    ctx.write(response);
                }
            }
            ctx.flush();
        }

    }
}
